from django.db import transaction
from django.db.models import Q
from django.http import JsonResponse, request
from admin import status_code
from common.models import TbUser, TbNewsInfo
from time import time

# 管理员注册登录注销


def show_user(request):
    '''
    展示用户
    :param request:
    :return:
    '''
    if request.method == 'GET':
        try:
            user = TbUser.objects.all()[0]
            data={}
            data['msg'] = status_code.SUCCESS
            data['name'] = user.name
            data['sex'] = user.sex
            data['email'] = user.email
        except:
            return JsonResponse({'msg': status_code.DATABASE_ERROR})
        return JsonResponse(data)


@transaction.atomic()
def deal_with_user(request):
    '''
    处理用户：警告，封禁
    :param request:
    :return:
    '''
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        user_status = request.POST.get('user_status')
        if user_id:
            users = TbUser.objects.all()
            user = TbUser.objects.filter(id=user_id).first()

            # 保存用户状态
            user.status = user_status
            user.save()

            # 获取警告／封禁信息
            title = request.POST.get('title')
            user_status = request.POST.get('user_status')
            content = request.POST.get('content')
            expire_time = request.POST.get('expire_time')
            # 保存信息
            new = TbNewsInfo.objects.all()
            new.news_type = user_status
            new.title = title
            new.content = content
            new.expire_time = expire_time
            new.create_time = time()
            new.auther = request.User
            new.save()

            # 封禁处理
            # 登录的时候判断该用户是否被封禁 （status == 2）
        return JsonResponse(status_code.SUCCESS)


@transaction.atomic()
def news(request):
    '''
    显示行业（3）和合作方（4）消息，更改消息
    :param request:
    :return:
    '''
    news_type_three = TbNewsInfo.objects.filter(Q(news_type=3) | Q(news_type=4))
    news_type_four = TbNewsInfo.objects.filter(news_type=4)

    data = {}
    new_three = [new.to_dict() for new in news_type_three]
    new_four = [new.to_dict() for new in news_type_four]

    if request.method == 'GET':
        data['news_three'] = new_three
        data['news_four'] = new_four
        data['msg'] = status_code.SUCCESS
        return JsonResponse(data)

    if request.method == 'POST':
        news_id = request.POST.get('news_id')
        news = TbNewsInfo.objects.get(id=news_id).first()
        news.title = request.POST.get('title') if request.POST.get('title') else 1
        news.content = request.POST.get('content') if request.POST.get('content') else 1
        news.auther = request.POST.get('auther') if request.POST.get('auther') else 1
        news.expire_time = request.POST.get('expire_time') if request.POST.get('expire_time') else 1
        news.save()
        return JsonResponse(data)





